package com.chenyanqing.config;

import com.chenyanqing.pojo.MapperStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XMLMapperBuilder {


    private Configuration configuration;


    public XMLMapperBuilder(Configuration configuration){
        this.configuration= configuration;
    }


    /**
     * 解析xml配置文件
     * @return
     */
    public void parseMapper(InputStream inputStream) throws Exception {
        Document document = new SAXReader().read(inputStream);
        Element element = document.getRootElement();

        String namespace = element.attributeValue("namespace");
        //解析mapper文件中的查询语句
          List<Element> selectList = element.selectNodes("//select");
        //组装成MapperStatement对象
        Map<String, MapperStatement>  map = getSelectStatementMap(namespace,selectList,ExecuteSQLType.SELECT);
        this.configuration.getMap().putAll(map);


        //添加
        List<Element> insertNodes = element.selectNodes("//insert");
        //组装成MapperStatement对象
        Map<String, MapperStatement>  insertMap = getSelectStatementMap(namespace,insertNodes,ExecuteSQLType.INSERT);
        this.configuration.getMap().putAll(insertMap);



        //更新
        List<Element> updateNodes = element.selectNodes("//update");
        //组装成MapperStatement对象
        Map<String, MapperStatement>  upMap = getSelectStatementMap(namespace,updateNodes,ExecuteSQLType.UPDATE);
        this.configuration.getMap().putAll(upMap);


        //删除
        List<Element> deleteNodes = element.selectNodes("//delete");
        //组装成MapperStatement对象
        Map<String, MapperStatement>  delteMap = getSelectStatementMap(namespace,deleteNodes,ExecuteSQLType.DELETE);
        this.configuration.getMap().putAll(delteMap);
    }


    private Map<String, MapperStatement> getSelectStatementMap(String namespace,List<Element> elementlist,ExecuteSQLType sqlType){
        Map<String, MapperStatement> map  = new HashMap<>();
        for (Element element : elementlist) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("paramType");
            String  sql = element.getTextTrim();
            MapperStatement statement = new MapperStatement(id,sql,parameterType,resultType,sqlType);
            map.put(namespace+"."+id,statement);
        }
        return map;
    }



}
